#include "stdafx.h"

extern WSASetLastError_proxy_t pTrueWSASetLastError;

int getsockname_proxy ( 
    __in  SOCKET           s,
    __out struct sockaddr* addr,
    __inout int*           addrlen
    )
{
    try
    {
    //SEND
        Header header(GetCurrentThreadId(), "getsockname");
        getsockname_in_inout getsocknameIN(s, addrlen);

        std::vector<char> out_buffer;
        Serialize(header, getsocknameIN, out_buffer);

        SendToClient (out_buffer);

    //RECEIVE()
        getsockname_out_inout getsocknameOUT;

        std::vector<char> in_buffer;
        
        RecvFromClient (in_buffer, header);
        Deserialize deserialize(in_buffer);
        deserialize(getsocknameOUT);

        if(getsocknameOUT.wsa_last_error_ != 0) 
        {
            pTrueWSASetLastError(getsocknameOUT.wsa_last_error_);
            return SOCKET_ERROR;
        }
        if (addr)
        {
            memcpy(addr, getsocknameOUT.addr_, sizeof(sockaddr));
        }
        if (addrlen)
        {
            *addrlen = *getsocknameOUT.addrlen_;
        }
        return 0;
    }
    catch (std::exception& ex)
    {
        LOG(plog::error) << "getsockname: " << ex.what();
    }
    pTrueWSASetLastError (WSAEWOULDBLOCK);
    return SOCKET_ERROR;
}
